/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package main;

import connectDB.ConnectDB;
import DAO.CodeName;
import java.awt.Color;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

public class frm_STAFF_A04 extends javax.swing.JFrame {

    private CodeName getCodeName;
    private ConnectDB conn4;
    private String EmpCode;
    private Date date;
    private DefaultTableModel tableModel;
    private int month;
    private int year;

    public frm_STAFF_A04(ConnectDB conn3, String EmpCode, Date date) {
        initComponents();
        setLocation(400, 200);
        setResizable(false);
        this.EmpCode = EmpCode;
        this.conn4 = conn3;
        this.date = date;
        getCodeName = new CodeName();
        tableModel = new DefaultTableModel();


        //load Month
        Calendar cal = Calendar.getInstance();
        cal.setTime(this.date);
        year = cal.get(Calendar.YEAR);
        month = cal.get(Calendar.MONTH);
        //excuteQueryA04();
        loadLabel();
        loadMonth();
        loadDataTable();
    }

    private void loadLabel() {
        try {
            ResultSet rs = null;
            String query = "SELECT ";
            query += " * ";
            query += "FROM ";
            query += "EMPLOYEE_MST EMP, ";
            query += "COMPANY_MST COM ";
            query += "WHERE ";
            query += "EMP.COM_CODE = COM.COM_CODE ";
            query += "AND ";
            query += "EMP.EMP_CODE = '" + EmpCode + "'";

            rs = conn4.excuteQuery(query);

            while (rs.next()) {
                lbComName.setText(rs.getString("COM_NAME").trim());
                lbEmpName.setText(rs.getString("EMP_LAST_NAME").trim() + " " + rs.getString("EMP_FIRST_NAME").trim());
                // Check trạng tháng công ty đã bị deleted
                if (rs.getString("COM_FLAG_DELETE").trim().equals("1")) {
                    lbComName.setForeground(Color.red);
                }
            }

        } catch (Exception e) {
            System.out.println("Wrong in loadLabel A04");
        }
    }

    private void loadMonth() {
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM");
        Calendar cal = Calendar.getInstance();
        cal.set(year, month, 1);
        lbMonth.setText(dateFormat.format(cal.getTime()));
    }

    private void loadDataTable() {
        // Remove tất cả các ROW trước khi tạo
        while (tableModel.getRowCount() > 0) {
            tableModel.removeRow(0);
        }

        // Load Column name
        Object[] colName = {"", "Day", "Working Class", "Start Class", "End Class", "Start Time", "EndTime", "Note", "Checked"};
        tableModel.setColumnIdentifiers(colName);

        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Calendar cal = Calendar.getInstance();
        cal.set(year, month, 1);

        int day = 1;
        int dayOfMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        int numCol = tableModel.getColumnCount();
        ArrayList<String> rowData = new ArrayList<String>();

        try {

            for (int rowNo = 1; rowNo <= dayOfMonth; rowNo++) {     // Duyệt row theo ngày của tháng
                cal.set(year, month, rowNo);
                String today = dateFormat.format(cal.getTime());

                // Select dữ liệu theo EMP_CODE và CAL_YMD
                ResultSet rs = null;
                String query = "SELECT ";
                query += "* ";
                query += "FROM ";
                query += "WORKTIME WRK ";
                query += "WHERE ";
                query += "WRK.EMP_CODE = '" + EmpCode + "' ";
                query += "AND ";
                query += "WRK.CAL_YMD = '" + today + "'";
                rs = conn4.excuteQuery(query);

                for (int colNo = 1; colNo <= 9; colNo++) {     // Duyệt từng column để view value
                    if (colNo == 1) {    // Cột thứ nhất : Hiển thị ngày của tháng
                        rowData.add("" + rowNo);
                    } else if (colNo == 2) { // Cột thứ 2 : hiển thị tên của ngày trong tuần
                        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
                        String dayName = getDayOfWeekName(dayOfWeek);
                        rowData.add(dayName);
                    } else {
                        String workClass = "";
                        String startClass = "";
                        String endClass = "";
                        String startTime = "";
                        String endTime = "";
                        String Note = "";
                        String Checked = "";
                        while (rs.next()) {
                            workClass = rs.getString("WRK_KBN").trim();
                            startClass = rs.getString("WRK_GO_KBN").trim();
                            endClass = rs.getString("WRK_LEFT_KBN").trim();
                            startTime = rs.getString("WRK_START_TIME").trim();
                            endTime = rs.getString("WRK_END_TIME").trim();
                            Note = rs.getString("WRK_NOTE").trim();
                            Checked = rs.getString("WRK_FLAG_CHECK").trim();
                        }
                        // Get code name của các data lấy từ database ra
                        // WORKCLASS
                        if (!workClass.isEmpty()) {
                            rowData.add(getCodeName.getWorkClass(workClass));
                        }
                        // START CLASS
                        if (!startClass.isEmpty()) {
                            rowData.add(getCodeName.getStartClass(startClass));
                        }

                        // END CLASS
                        if (!endClass.isEmpty()) {
                            rowData.add(getCodeName.getEndClass(endClass));
                        }

                        rowData.add(startTime);
                        rowData.add(endTime);
                        rowData.add(Note);

                        // CHECKED
                        if (!Checked.isEmpty()) {
                            rowData.add(getCodeName.getChecked(Checked));
                        }
                    }
                }
                tableModel.addRow(rowData.toArray());
                rowData.clear();;
            }
            tblEmp.setModel(tableModel);
        } catch (SQLException ex) {
            System.out.println("Wrong in Result Set in load DataTable() A04");
        }


    }

    public String getDayOfWeekName(int day) {
        if (day == 1) {
            return "Sun";
        } else if (day == 2) {
            return "Mon";
        } else if (day == 3) {
            return "Tue";
        } else if (day == 4) {
            return "Wed";
        } else if (day == 5) {
            return "Thu";
        } else if (day == 6) {
            return "Fri";
        } else if (day == 7) {
            return "Sat";
        } else {
            System.out.println("Day not invalid in getdayOfWeek()");
            return "";
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblEmp = new javax.swing.JTable();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        lbEmpName = new javax.swing.JLabel();
        lbMonth = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        lbComName = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        btBack = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        btUpdate = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        btPrevMonth = new javax.swing.JButton();
        butNextMonth = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        tblEmp.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {},
                {},
                {},
                {},
                {},
                {},
                {},
                {},
                {},
                {},
                {},
                {},
                {},
                {},
                {},
                {},
                {},
                {},
                {},
                {},
                {},
                {},
                {},
                {},
                {},
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(tblEmp);

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel3.setText("Employee Name");

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel4.setText("Month");

        lbEmpName.setText("XXXXXXXXXXX");

        lbMonth.setText("yyyy/MM");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel2.setText("Company Name");

        lbComName.setText("XXXXXXXXXXX");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 738, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4)
                    .addComponent(jLabel2))
                .addGap(39, 39, 39)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbEmpName)
                    .addComponent(lbMonth)
                    .addComponent(lbComName))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(lbComName))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbEmpName)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbMonth)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 20)); // NOI18N
        jLabel1.setText("SEARCH");

        btBack.setText("BACK");
        btBack.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btBackActionPerformed(evt);
            }
        });

        jButton6.setText("Print");

        btUpdate.setText("Update");
        btUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btUpdateActionPerformed(evt);
            }
        });

        jButton4.setText("Delete");

        btPrevMonth.setText("Previous Month");
        btPrevMonth.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btPrevMonthActionPerformed(evt);
            }
        });

        butNextMonth.setText("Next Month");
        butNextMonth.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                butNextMonthActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(btBack)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btUpdate)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btPrevMonth)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(butNextMonth))
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addGap(341, 341, 341))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addComponent(jLabel1)
                .addGap(37, 37, 37)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(butNextMonth)
                    .addComponent(btBack)
                    .addComponent(btPrevMonth)
                    .addComponent(jButton4)
                    .addComponent(btUpdate)
                    .addComponent(jButton6))
                .addContainerGap(19, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btBackActionPerformed
        // TODO add your handling code here:
        setVisible(false);
        frm_STAFF_A02 frm2 = new frm_STAFF_A02(EmpCode, conn4);
        frm2.setVisible(true);
    }//GEN-LAST:event_btBackActionPerformed

    private void btPrevMonthActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btPrevMonthActionPerformed
        // TODO add your handling code here:
        month--;
        loadMonth();
        loadDataTable();
    }//GEN-LAST:event_btPrevMonthActionPerformed

    private void butNextMonthActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butNextMonthActionPerformed
        // TODO add your handling code here:
        month++;
        loadMonth();
        loadDataTable();
    }//GEN-LAST:event_butNextMonthActionPerformed

    private void btUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btUpdateActionPerformed
        // TODO add your handling code here:
        int rowChoose = tblEmp.getSelectedRow();    // trả về index của row được chọn
        if (rowChoose == -1) {  // index = -1 nếu chưa chọn
            JOptionPane.showMessageDialog(null, "Please choose a day to Update!");
            return;
        }

        String checked = tableModel.getValueAt(rowChoose, 8).toString();  // Lấy giá trị của hàng chọn, cột 8 (cột Checked)
        if (checked.equals("Yes")) {    // Đã được admin xác nhận thì ko được Update
            JOptionPane.showMessageDialog(null, "This day have been checked by Admin! You can't Update");
            return;
        }
        if (checked.equals("")) {
            JOptionPane.showMessageDialog(null, "Not have any record to update");
            return;
        }


        Calendar cal = Calendar.getInstance();
        cal.set(year, month, rowChoose + 1);
        date = cal.getTime();       // Lấy ngày vừa chọn để update

        frm_STAFF_A03 frm3 = new frm_STAFF_A03(EmpCode, conn4, date);
        frm3.setVisible(true);
        this.dispose();

    }//GEN-LAST:event_btUpdateActionPerformed
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btBack;
    private javax.swing.JButton btPrevMonth;
    private javax.swing.JButton btUpdate;
    private javax.swing.JButton butNextMonth;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton6;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lbComName;
    private javax.swing.JLabel lbEmpName;
    private javax.swing.JLabel lbMonth;
    private javax.swing.JTable tblEmp;
    // End of variables declaration//GEN-END:variables
}
